<!--SMT站位表 编辑-->
<template>
  <div>
    <el-dialog
      top="5vh"
      width="85%"
      title="编辑"
      append-to-body
      custom-class="smtStandDialog"
      v-if="showEditDialog"
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      :visible.sync="showEditDialog"
      @close="handleEditReset"
    >
      <div class="sail-header-dialog-content">
        <avue-form ref="editRef" v-model="editDialog.form" :option="editDialog.option" @submit="handleEditSubmit" @reset-change="handleEditReset">
          <template slot="partNos">
            <el-input size="mini" placeholder="请选择产品编码" v-model="editDialog.form.partNos" :readonly="true" class="input-with-select">
              <el-button slot="append" icon="el-icon-search" @click="handleSelectPartNos"></el-button>
            </el-input>
          </template>
          <template slot="machineBrand">
            <el-input size="mini" placeholder="请选择设备品牌" v-model="editDialog.form.machineBrand" :readonly="true" class="input-with-select">
              <el-button slot="append" icon="el-icon-search" @click="handleSelectMachineBrand"></el-button>
            </el-input>
          </template>
          <template slot="machineModel">
            <el-input size="mini" placeholder="请选择设备型号" v-model="editDialog.form.machineModel" :readonly="true" class="input-with-select">
              <el-button slot="append" icon="el-icon-search" @click="handleSelectMachineModel"></el-button>
            </el-input>
          </template>
        </avue-form>
        <avue-crud
          ref="editCrud"
          v-model="editDialog.tableForm"
          :option="editDialog.tableOption"
          :data="editDialog.tableData"
          :table-loading="editDialog.loading"
          @row-save="handleEditSave"
          @row-update="handleEditUpdate"
          @selection-change="selectionEditChange"
        >
          <template slot="menuLeft">
            <el-button type="primary" size="small" icon="el-icon-plus" @click="handleEditAdd">新 增</el-button>
            <el-button type="danger" size="small" icon="el-icon-delete" @click="handleEditDel">删 除</el-button>
          </template>
          <template slot="menu" slot-scope="scope">
            <el-button type="text" size="small" :icon="scope.row.$cellEdit ? 'el-icon-plus' : 'el-icon-edit'" @click="handleRowCell(scope.row, scope.index)">
              {{ scope.row.$cellEdit ? '保存' : '编辑' }}
            </el-button>
            <el-button v-if="scope.row.$cellEdit" type="text" size="small" icon="el-icon-cancel" @click="handleRowCancel(scope.row, scope.index)">取消</el-button>
            <el-button v-else type="text" size="small" icon="el-icon-delete" @click="handleEditRowDel(scope.row, scope.index)">删除</el-button>
          </template>
          <template slot-scope="{ row }" slot="quantity">
            <span v-if="!row.$cellEdit">{{ row.quantity }}</span>
            <avue-input-number v-else size="mini" v-model="row.quantity" :minRows="1" :disabled="!row.$cellEdit"></avue-input-number>
          </template>
          <template slot-scope="{ row }" slot="side">
            <span v-if="!row.$cellEdit">{{ row.side }}</span>
            <avue-select v-else size="mini" v-model="row.side" :dic="sideOption" :disabled="!row.$cellEdit"> </avue-select>
          </template>
          <template slot-scope="scope" slot="partNo">
            <span v-if="!scope.row.$cellEdit">{{ scope.row.partNo }}</span>
            <el-input v-else size="mini" placeholder="请输入物料编码" v-model="scope.row.partNo" :disabled="true" class="input-with-select">
              <el-button slot="append" icon="el-icon-search" @click="handleWlbm(scope.index)"></el-button>
            </el-input>
          </template>
          <template slot-scope="{ row }" slot="partModel">
            <span v-if="!row.$cellEdit">{{ row.partModel }}</span>
            <avue-input v-else size="mini" v-model="row.partModel" :disabled="true"></avue-input>
          </template>
          <template slot-scope="scope" slot="replacePartNo">
            <el-button v-if="scope.row.$cellEdit" type="text" size="small" @click="handleTdlEdit(scope.row, scope.index)">编辑</el-button>
            <el-button v-else type="text" size="small" @click="handleTdlDetail(scope.row, scope.index)">详情</el-button>
          </template>
        </avue-crud>
        <div class="remark">
          <div class="input-label"><span style="color: #f56c6c; margin-right: 4px">*</span>修改原因:</div>
          <div :class="['input-text', { 'invalid-input': isValid }]">
            <el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="editDialog.form.remark" @blur="handleBlur"> </el-input>
          </div>
          <span class="invalid-span" v-if="isValid">请输入修改原因</span>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" icon="el-icon-check" @click="handleFooterEditSubmit">保存</el-button>
        <el-button size="small" icon="el-icon-delete" @click="handleFooterEditReset">取消</el-button>
      </span>
    </el-dialog>
    <!--编辑替代料 -->
    <el-dialog
      custom-class="replaceMateriaDialog"
      append-to-body
      :close-on-click-modal="false"
      :title="replaceMateriaDialog.title"
      :visible.sync="replaceMateriaDialog.visible"
      width="50%"
      top="7vh"
    >
      <div class="sail-header-dialog-content">
        <el-form
          v-loading="replaceMateriaDialog.form.loading"
          v-if="!replaceMateriaReadOnly"
          :model="replaceMateriaDialog.form"
          ref="replaceMateriaDialogRef"
          label-width="100px"
          class="demo-dynamic"
        >
          <div class="row" v-for="(item, index) in replaceMateriaDialog.form.domains" :key="index">
            <el-form-item
              label="替代料编码"
              :key="item.key"
              :prop="'domains.' + index + '.partNo'"
              :rules="{
                required: true,
                message: '请选择替代料编码',
                trigger: 'blur'
              }"
            >
              <el-input size="mini" placeholder="请选择替代料编码" v-model="item.partNo" :disabled="true" class="input-with-select">
                <el-button slot="append" icon="el-icon-search" @click="handleReplaceCode(index)"></el-button>
              </el-input>
            </el-form-item>
            <el-form-item label="用量:" prop="usage" class="usageItem">
              <el-input-number size="mini" v-model="item.usage" :precision="0" controls-position="right" :min="1"></el-input-number>
              <el-button size="mini" class="deleteIcon" type="danger" icon="el-icon-delete" circle @click="removeDomain(item, index)"></el-button>
            </el-form-item>
          </div>
          <div class="addIcon">
            <el-button size="mini" icon="el-icon-plus" circle @click="addDomain"></el-button>
          </div>
        </el-form>
        <avue-crud v-else :table-loading="replaceMateriaDialog.loading" :data="replaceMateriaDialog.tableData" :option="replaceMateriaDialog.tableOption"></avue-crud>
      </div>
      <span slot="footer" class="dialog-footer" v-if="!replaceMateriaReadOnly">
        <el-button size="small" type="primary" icon="el-icon-check" @click="handleReplaceSubmit">保存</el-button>
        <el-button size="small" icon="el-icon-delete" @click="handleReplaceReset">取消</el-button>
      </span>
    </el-dialog>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
  </div>
</template>

<script>
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import smtStandImport from '@/views/product/components/smtStandImport.vue';
import {
  getList,
  getDetail,
  getTrackList,
  getLogDetail,
  add,
  update,
  remove,
  getTrackReplaceDetail,
  addTrack,
  removeTrack,
  verifyMachineCodeOrPartNo,
  getSmtType,
  updateTable
} from '@/api/product/smtStandTable';
import { mapGetters } from 'vuex';
import { MACHINE_BRAND_COLUMN, MACHINE_BRAND_COLUMN_EDIT, MACHINE_COLUMN_EDIT, MACHINE_MODEL_COLUMN, MACHINE_MODEL_COLUMN_EDIT } from '@/views/product/smtStandTable';

export default {
  components: {
    GlobalModalTemplate,
    smtStandImport
  },
  name: 'smtEdit',
  props: {
    showEditDialog: {
      type: Boolean,
      default: false
    },
    smtType: {
      type: String,
      default: 'MACHINE_BRAND'
    }
  },
  watch: {
    smtType: {
      handler(val) {
        this.setEditInfo(val);
      },
      immediate: true
    }
  },
  data() {
    return {
      rowId: null,
      isValid: false,
      sideOption: [
        { label: 'B', value: 'B' },
        { label: 'T', value: 'T' },
        { label: 'B/T', value: 'B/T' }
      ],
      editDialog: {
        form: {},
        loading: false,
        option: {
          searchShow: true,
          searchMenuSpan: 6,
          menuPosition: 'right',
          submitBtn: false,
          emptyBtn: false,
          group: [
            {
              label: '基础信息',
              prop: 'equipmentInfo',
              arrow: false,
              icon: 'el-icon-vertical-bar',
              labelWidth: 100,
              column: [
                {
                  label: '产品编码',
                  prop: 'partNos',
                  // disabled: true,
                  span: 6,
                  appendClick: () => {
                    this.openUserCommonModal({ type: 'productCode' });
                  },
                  rules: [
                    {
                      required: true,
                      message: '请选择产品编码',
                      trigger: 'blur'
                    }
                  ]
                },
                {
                  label: '产品名称',
                  prop: 'partNames',
                  // disabled: true,
                  span: 6,
                  rules: [
                    {
                      required: true,
                      message: '请选择产品名称',
                      trigger: 'blur'
                    }
                  ]
                },
                {
                  label: '站位表名称',
                  prop: 'name',
                  span: 6,
                  rules: [
                    {
                      required: true,
                      message: '请输入站位表名称',
                      trigger: 'blur'
                    }
                  ]
                },
                // {
                //   label: '机台号',
                //   prop: 'machineCode',
                //   span: 6,
                //   rules: [
                //     {
                //       required: true,
                //       message: '请选择设备品牌',
                //       trigger: 'blur'
                //     }
                //   ]
                // },
                {
                  label: '设备品牌',
                  prop: 'machineBrand',
                  span: 6,
                  // disabled: true,
                  control: (val, form) => {
                    if (this.smtType === 'MACHINE') {
                      return {
                        machineBrand: {
                          display: false
                        }
                      };
                    } else {
                      return {
                        machineBrand: {
                          display: true
                        }
                      };
                    }
                  }
                },
                {
                  label: '面向',
                  prop: 'side',
                  type: 'select',
                  span: 6,
                  props: {
                    label: 'dictValue',
                    value: 'dictKey'
                  },
                  // disabled: true,
                  dicUrl: '/api/blade-system/dict/dictionary?code=side_type',
                  rules: [
                    {
                      required: true,
                      message: '请输入面向',
                      trigger: 'blur'
                    }
                  ]
                },
                {
                  label: '站位表版本',
                  prop: 'tableVersion',
                  // disabled: true,
                  span: 6
                },
                {
                  label: '站位表编码',
                  disabled: true,
                  prop: 'code',
                  span: 6,
                  rules: [
                    {
                      required: true,
                      message: '请输入站位表编码',
                      trigger: 'blur'
                    }
                  ]
                }
              ]
            },
            {
              label: '站位表详情',
              labelWidth: 100,
              prop: 'equipmentInfo',
              arrow: false,
              icon: 'el-icon-vertical-bar',
              column: []
            }
          ]
        },
        tableOption: {
          rowKey: 'trackId',
          height: '250px',
          maxHeight: '250px',
          calcHeight: 30,
          tip: false,
          searchShow: false,
          border: true,
          index: true,
          indexLabel: '序号',
          viewBtn: false,
          editBtn: false,
          addBtn: false,
          page: false,
          delBtn: false,
          cellBtn: false,
          cancelBtn: false,
          labelWidth: 130,
          selection: true,
          refreshBtn: false,
          columnBtn: false,
          highlightCurrentRow: true, // 选中高亮
          dialogClickModal: false,
          menuWidth: 200,
          column: [
            {
              label: '站号',
              prop: 'trackNo',
              cell: true
            },
            {
              label: '飞达规格',
              prop: 'feederSpecRequired',
              cell: true
            },
            {
              label: '物料编码',
              width: 150,
              prop: 'partNo'
            },
            {
              label: '物料规格',
              prop: 'partModel'
            },
            {
              label: '位号',
              prop: 'positionNo',
              cell: true
            },
            {
              label: '用量',
              prop: 'quantity'
            },
            {
              label: '面向',
              prop: 'side',
              type: 'select',
              props: {
                label: 'dictValue',
                value: 'dictKey'
              },
              disabled: true,
              dicUrl: '/api/blade-system/dict/dictionary?code=side_type',
              rules: [
                {
                  required: true,
                  message: '请输入面向',
                  trigger: 'blur'
                }
              ]
            },
            // {
            //   label: '物料品牌',
            //   prop: 'materialBrand',
            //   cell: true
            // },
            // {
            //   label: '物料供应商',
            //   prop: 'vendorCode',
            //   cell: true
            // },
            {
              label: '替代料',
              width: 60,
              prop: 'replacePartNo'
            }
          ]
        },
        rowIndex: -1,
        selectionList: [],
        tableData: [],
        tableForm: {},
        tablePage: {
          pageSize: 20,
          currentPage: 1,
          total: 0
        }
      },
      replaceMateriaDialog: {
        title: '编辑',
        visible: false,
        rowIndex: -1,
        form: {
          loading: false,
          domains: [
            {
              partNo: '',
              partName: '',
              usage: ''
            }
          ]
        },
        option: {
          submitText: '保存',
          emptyText: '取消',
          menuPosition: 'right'
        },
        loading: false,
        tableData: [],
        tableOption: {
          height: '500px',
          maxHeight: '500px',
          calcHeight: 30,
          tip: false,
          searchShow: false,
          border: true,
          index: true,
          indexLabel: '序号',
          viewBtn: false,
          editBtn: true,
          addBtn: false,
          delBtn: false,
          labelWidth: 130,
          menu: false,
          refreshBtn: false,
          columnBtn: false,
          highlightCurrentRow: true, // 选中高亮
          dialogClickModal: false,
          column: [
            {
              label: '替代料编码',
              prop: 'partNo'
            },
            {
              label: '替代料名称',
              prop: 'partName'
            },
            {
              label: '用量',
              prop: 'usage'
            }
          ]
        }
      },
      form: {},
      query: {},
      cloneForm: {},
      loading: true,
      selectionList: [],
      data: [],
      visibile: false,
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime() //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.smttable_add, false),
        viewBtn: this.vaildData(this.permission.smttable_view, false),
        delBtn: this.vaildData(this.permission.smttable_delete, false),
        editBtn: this.vaildData(this.permission.smttable_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    replaceMateriaReadOnly() {
      if (this.replaceMateriaDialog.title == '编辑替代料') {
        return false;
      } else {
        return true;
      }
    }
  },
  methods: {
    // 获取详情 基础信息
    async getData(id) {
      this.rowId = id;
      getDetail(this.rowId).then((res) => {
        let data = res.data.data;
        this.editDialog.form = this._cloneDeep(data);
      });
      await this.getTable();
    },
    // 获取详情 站位表
    async getTable() {
      this.editDialog.loading = true;
      try {
        const res = await getTrackList(1, 1000, this.rowId);
        let data = res.data.data;
        this.editDialog.tableData = data.records;
        this.editDialog.loading = false;
      } catch (e) {
        console.warn(e);
      }
    },
    setEditInfo(val) {
      const tableMap = {
        MACHINE_BRAND: MACHINE_BRAND_COLUMN_EDIT,
        MACHINE: MACHINE_COLUMN_EDIT,
        MACHINE_MODEL: MACHINE_MODEL_COLUMN_EDIT,
        HUI_YAN: MACHINE_MODEL_COLUMN
      };
      let column;
      if (!tableMap[val]) {
        column = MACHINE_BRAND_COLUMN;
      } else {
        column = tableMap[val];
      }
      this.$set(this.editDialog.option.group[0], 'column', column);
    },
    handleEdit(row, index) {
      this.showEditDialog = true;
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
          this.cloneForm = this._cloneDeep(res.data.data);
        });
      }
      if (['add', 'edit'].includes(type)) {
      }
      done();
    },

    openUserCommonModal(params) {
      let { type } = params;
      this.visibile = true;
      this.tableOption = {
        modalTitle: '选择产品信息（双击进行选择）',
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        searchLabelWidth: 90
      };
      this.tableOption.url = type === 'partNo' ? '/api/mes-admin/part-master/page?semifinished=true' : '/api/mes-admin/part-master/page';
      this.tableOption.isPage = true;
      this.tableOption.query = type === 'partNo' ? '' : { partType: 'MATERIAL' };
      this.tableOption.templateName = 'NOWORKPARTMASTER';
      switch (type) {
        case 'productCode':
          this.modalName = 'partmasterModal';
          break;
        case 'editProductCode':
          this.modalName = 'editPartmasterModal';
          break;
        case 'partNo':
          this.modalName = 'partNo';
          break;
        case 'replaceProductCode':
          this.modalName = 'replacePartmasterModal';
          break;
        default:
          break;
      }
    },
    openMachineCommonModal() {
      this.visibile = true;
      this.tableOption = {
        modalTitle: '选择设备信息（双击进行选择）',
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        searchLabelWidth: 90
      };
      this.tableOption.url = '/api/mes-product/ems-equipment/page';
      this.tableOption.isPage = true;
      this.tableOption.query = { equipmentType: 'MACHINE' };
      this.tableOption.templateName = 'EQUIPMENT';
      this.modalName = 'machineModal';
    },
    openMachineBrandCommonModal() {
      this.visibile = true;
      this.tableOption = {
        modalTitle: '选择设备信息（双击进行选择）',
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        searchLabelWidth: 90
      };
      this.tableOption.url = '/api/mes-product/ems-equipment/page';
      this.tableOption.isPage = true;
      this.tableOption.query = { equipmentType: 'MACHINE' };
      this.tableOption.templateName = 'EQUIPMENT';
      this.modalName = 'machineBrandModal';
    },
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'partmasterModal':
          this.importDialog.form.partNo = this._get(rowData, 'partNo', '');
          this.importDialog.form.partName = this._get(rowData, 'name', '');
          break;
        case 'editPartmasterModal':
          let findIndex = this.editDialog.tableData.findIndex((d) => d.$index == this.editDialog.rowIndex);
          this.editDialog.tableData[findIndex].partNo = this._get(rowData, 'partNo', '');
          this.editDialog.tableData[findIndex].partModel = this._get(rowData, 'partModel', '');
          break;
        case 'replacePartmasterModal':
          this.replaceMateriaDialog.form.domains[this.replaceMateriaDialog.rowIndex].partName = this._get(rowData, 'name', '');
          this.replaceMateriaDialog.form.domains[this.replaceMateriaDialog.rowIndex].partNo = this._get(rowData, 'partNo', '');
          break;
        case 'partNo':
          this.editDialog.form.partNos = this._get(rowData, 'partNo', '');
          this.editDialog.form.partNames = this._get(rowData, 'name', '');
          this.editDialog.form.partModel = this._get(rowData, 'partModel', '');
          break;
        case 'machineBrandModal':
          this.editDialog.form.machineBrand = this._get(rowData, 'brand', '');
          break;
        case 'machineModal':
          this.editDialog.form.machineModel = this._get(rowData, 'model', '');
          break;
        default:
          break;
      }
    },
    handleEditSave(form, done) {
      done();
      // if (!form.trackNo) {
      //   done();
      //   this.$message.warning('请输入站号');
      //   return;
      // }
      // form.tableId = this.rowId;
      // form.partNos = this.editDialog.form.partNos;
      // // form.replacePartNo = JSON.stringify(form.replacePartNo || '[]');
      // addTrack(form)
      //   .then(() => {
      //     this.$message.success('保存成功');
      //   })
      //   .catch((err) => {})
      //   .finally(() => {
      //     done();
      //   });
    },
    handleEditUpdate(form, index, done, loading) {
      loading();
      done();
    },
    handleEditAdd() {
      this.editDialog.tableData.unshift({
        tableId: this.rowId,
        partNos: this.editDialog.form.partNos,
        trackNo: '',
        feederSpecRequired: '',
        partNo: '',
        partModel: '',
        positionNo: '',
        quantity: 1,
        side: 'B',
        machineCode: '',
        vendorCode: '',
        replacePartNo: ''
      });
    },
    handleEditDel() {
      if (this.editDialog.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.editDialog.tableData = this.editDialog.tableData.filter((d) => !this.editDialog.selectionList.map((list) => list.$index).includes(d.$index));
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        // let ids = this.editDialog.selectionList.map((list) => list.trackId).join(',');
        // removeTrack(ids)
        //   .then((res) => {
        //     this.$message({
        //       type: 'success',
        //       message: '删除成功!'
        //     });
        //     this.getTable();
        //   })
        //   .catch((err) => {});
      });
    },
    handleRowCell(row, index) {
      this.$refs.editCrud.rowCell(row, index);
    },
    handleRowCancel(row, index) {
      this.$refs.editCrud.rowCancel(row, index);
    },
    handleEditRowDel(row, index) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.editDialog.tableData.splice(index, 1);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        // this.getTable();
        // if (row.trackId) {
        //   removeTrack(row.trackId)
        //     .then((res) => {
        //       this.$message({
        //         type: 'success',
        //         message: '删除成功!'
        //       });
        //       this.getTable();
        //     })
        //     .catch((err) => {});
        // } else {
        //   this.editDialog.tableData.splice(index, 1);
        // }
      });
    },
    selectionEditChange(list) {
      this.editDialog.selectionList = list;
    },

    handleSelectPartNos() {
      this.openUserCommonModal({ type: 'partNo' });
    },
    handleSelectMachineBrand() {
      this.openMachineBrandCommonModal();
    },
    handleSelectMachineModel() {
      this.openMachineCommonModal();
    },
    handleWlbm(index) {
      this.editDialog.rowIndex = index;
      this.openUserCommonModal({ type: 'editProductCode' });
    },
    handleTdlEdit(row, index) {
      this.editDialog.rowIndex = index;
      this.replaceMateriaDialog.visible = true;
      this.replaceMateriaDialog.title = '编辑替代料';
      if (!row.trackId) {
        return;
      }
      this.replaceMateriaDialog.form.loading = true;
      getTrackReplaceDetail(row.trackId)
        .then((res) => {
          let data = res.data.data;
          if (data && data.length > 0) {
            this.replaceMateriaDialog.form.domains = JSON.parse(data[0].replacePartNo || '[]');
          } else {
            this.replaceMateriaDialog.form.domains = [];
          }
        })
        .catch(() => {})
        .finally(() => {
          this.replaceMateriaDialog.form.loading = false;
        });
    },
    handleTdlDetail(row, index) {
      this.replaceMateriaDialog.visible = true;
      this.replaceMateriaDialog.title = '详情替代料';
      this.replaceMateriaDialog.tableData = [];
      if (!row.trackId) {
        return;
      }
      this.replaceMateriaDialog.loading = true;
      getTrackReplaceDetail(row.trackId)
        .then((res) => {
          let data = res.data.data;
          if (data && data.length > 0) {
            this.replaceMateriaDialog.tableData = JSON.parse(data[0].replacePartNo || '[]');
          } else {
            this.replaceMateriaDialog.tableData = [];
          }
        })
        .catch(() => {})
        .finally(() => {
          this.replaceMateriaDialog.loading = false;
        });
    },
    removeDomain(item) {
      var index = this.replaceMateriaDialog.form.domains.indexOf(item);
      if (index !== -1) {
        this.replaceMateriaDialog.form.domains.splice(index, 1);
      }
    },
    addDomain() {
      this.replaceMateriaDialog.form.domains.push({
        partNo: '',
        partName: '',
        usage: '',
        key: Date.now()
      });
    },
    handleReplaceCode(index) {
      this.replaceMateriaDialog.rowIndex = index;
      this.openUserCommonModal({ type: 'replaceProductCode' });
    },
    handleReplaceSubmit() {
      this.$refs['replaceMateriaDialogRef'].validate((valid) => {
        if (valid) {
          const rowIndex = this.editDialog.rowIndex;
          this.editDialog.tableData[rowIndex].replacePartNo = JSON.stringify(this.replaceMateriaDialog.form.domains);
          this.replaceMateriaDialog.visible = false;
        } else {
          return false;
        }
      });
    },
    handleReplaceReset() {
      this.$refs['replaceMateriaDialogRef'].resetFields();
      this.replaceMateriaDialog.visible = false;
    },

    // 编辑保存
    handleFooterEditSubmit() {
      if (!this.editDialog.form.remark) {
        this.isValid = true;
        this.$message.warning('请输入修改原因');
        return;
      }
      this.$refs.editRef.submit();
    },
    // 编辑取消
    handleFooterEditReset() {
      this.$refs.editRef.resetForm();
    },
    hasDuplicates(arr) {
      return new Set(arr).size !== arr.length;
    },
    handleBlur(e) {
      !e.target.value ? (this.isValid = true) : (this.isValid = false);
    },
    async handleEditSubmit(form, done) {
      let isEmptyData = this.editDialog.tableData.every((item) => {
        return item.trackNo && item.partNo;
      });
      if (this.isValid) {
        done();
        return;
      }
      if (!isEmptyData) {
        this.$message.warning('站位表详情数据中站号和物料编码不能为空，请仔细检查');
        done();
        return;
      }

      let isRepeatData = this.hasDuplicates(this.editDialog.tableData.map((t) => t.trackNo));
      if (isRepeatData) {
        this.$message.warning('站位表详情数据中出现重复站号，请仔细检查');
        done();
        return false;
      }
      const data = {
        smtTable: this.editDialog.form,
        smtTrackDTO: this.editDialog.tableData
      };
      try {
        const res = await updateTable(data);
        this.$message.success('操作成功');
        this.showEditDialog = false;
        this.isValid = false;
        this.$emit('closeEditDialog');
      } catch (e) {
        console.warn(e);
      }
      done();
    },
    handleEditReset() {
      this.showEditDialog = false;
      this.isValid = false;
      this.$emit('closeEditDialog');
    },
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .smtStandDialog {
  .el-dialog__body {
    padding: 0 20px;
  }
  .avue-form__menu--right {
    display: none;
  }
  .detailTitle {
    font-size: 16px;
    font-weight: bold;
    height: 50px;
    line-height: 50px;
    color: rgba(0, 0, 0, 0.85);
    border-bottom: 1px solid #eee;
  }
  .detailArea {
    .avue-crud__menu {
      display: none;
    }
  }
}
::v-deep .replaceMateriaDialog {
  .row {
    display: flex;
    .deleteIcon {
      margin-left: 10px;
    }
    .usageItem {
      .el-form-item__content {
        display: flex;
      }
    }
  }
  .addIcon {
    display: flex;
    justify-content: center;
  }
  .avue-crud__menu {
    display: none;
  }
}
.remark {
  margin-top: 24px;
  position: relative;
  .input-text {
    margin-top: 12px;
  }
  .input-label {
    margin-top: 12px;
  }
  .invalid-input {
    position: relative;
    ::v-deep .el-textarea__inner {
      border: 1px solid #f56c6c;
    }
  }
  .invalid-span {
    color: #f56c6c;
    font-size: 12px;
    line-height: 1;
    padding-top: 4px;
    position: relative;
    top: 0;
  }
}
</style>
